package com.luojialong.aop;

import com.luojialong.service.UserService;
import com.luojialong.utils.TimeUtils;
import com.luojialong.verification.MyCreateLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 根据@MyCreateLog的注解,获取器doMethod的值,来记录用户具体做什么
 * @author 罗家龙
 */
@Aspect
@Component
@Slf4j
public class UsingStatusCheckAop {


    @Resource
    private UserService userService;

    @Around("@annotation(myLog)")
    public Object doHandle(ProceedingJoinPoint point,MyCreateLog myLog) throws Throwable {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        String doMethod = myLog.doMethod();
        String requestURI = request.getRemoteHost();
        String remoteUser = request.getRemoteUser();
        Integer remotePort = request.getRemotePort();
        Date date = new Date();
        String time = TimeUtils.transferDatetimeFormat(date);
        long start = System.currentTimeMillis();
        Object proceed = point.proceed();
        long end = System.currentTimeMillis();
        log.info(String.format("用户%s通过地址:%s:%s,在:%s,使用了该系统,执行了:%s:的功能,执行的总时间为:%s ms", remoteUser,requestURI,remotePort,time,doMethod,(end -start) + ""));
        return proceed;
    }
}
